package dialog;

import android.content.Context;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.zx.theline.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.MyApplication;
import base.BaseDialog;
import greendao.ProtectMeasuresDao;
import greendao.SecurityRiskDao;
import greendao.entity.ProtectMeasures;
import greendao.entity.SecurityRisk;

/**
 * Created by zx on 2017/3/28.
 */

public class EditDangerPointDailog extends BaseDialog {

    Spinner sgxm;
    ListView mList;
    RadioGroup mRadioGroup;
    RadioButton xzq, bjq;
    LinearLayout bjq_layout, xzq_layout;
    TextView queding, quxiao;
    EditText bjq_edittext;
    //选中的内容
    TextView select_text;
    List<String> selectList;
    //根据List内ID从数据库提取数据填充给spinner
    List<Integer> datalist;
    List<String> SpinnerList;
    HashMap<String, Integer> mMap;
    //根据DBflag判断筛选安全风险内容：0 or 安全风险措施内容 ：1
    int DBflag;

    MyListAdapter mMyListAdapter;

    SecurityRiskDao mSecurityRiskDao;
    ProtectMeasuresDao mProtectMeasuresDao;

    List<SecurityRisk> SecurityRiskList;
    List<ProtectMeasures> ProtectMeasuresList;

    List<String> mListViewData;


    OnOkClickListener mOnOkClickListener;

    int ViewId;

    public EditDangerPointDailog(Context context, HashMap<String, Integer> mMap, int DBflag, int viewId) {
        super(context);
        this.mMap = mMap;
        this.DBflag = DBflag;
        this.ViewId = viewId;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_editdangerpoint);
        InitView();
        InitData();
        InitListen();
        this.setCanceledOnTouchOutside(false);
    }

    @Override
    protected void InitView() {
        sgxm = (Spinner) findViewById(R.id.sgxm);
        mList = (ListView) findViewById(R.id.listview);
        mRadioGroup = (RadioGroup) findViewById(R.id.RadioGroup);
        xzq = (RadioButton) findViewById(R.id.xzq);
        bjq = (RadioButton) findViewById(R.id.bjq);

        bjq_layout = (LinearLayout) findViewById(R.id.bjq_layout);
        xzq_layout = (LinearLayout) findViewById(R.id.xzq_layout);

        queding = (TextView) findViewById(R.id.queding);
        quxiao = (TextView) findViewById(R.id.quxiao);
        select_text = (TextView) findViewById(R.id.select_text);
        select_text.setMovementMethod(ScrollingMovementMethod.getInstance());
        bjq_edittext = (EditText) findViewById(R.id.bjq_edittext);
    }

    public void InitData() {
        selectList = new ArrayList<>();
        xzq.setChecked(true);
        mListViewData = new ArrayList<>();
        getSpinnerData();
        setSpinnerData();
    }


    @Override
    protected void InitListen() {
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.xzq) {
                    bjq_layout.setVisibility(View.GONE);
                    xzq_layout.setVisibility(View.VISIBLE);
                }
                if (checkedId == R.id.bjq) {
                    bjq_layout.setVisibility(View.VISIBLE);
                    xzq_layout.setVisibility(View.GONE);
                }
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将用户选择跟编辑的风险点 拼接
                String s;
                if(selectList.size()>0&&bjq_edittext.getText().toString().trim().length()>0){
                    s = select_text.getText().toString() +","+ bjq_edittext.getText().toString();
                }
                else if(selectList.size()>0&&bjq_edittext.getText().toString().trim().length()==0){
                    s = select_text.getText().toString();
                } else {
                    s = bjq_edittext.getText().toString();
                }

                mOnOkClickListener.OkClickListener(s, ViewId);
            }
        });
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditDangerPointDailog.this.dismiss();
            }
        });
        //给sgxm spinner添加事件，根据选择的内容，选取数据库相应数据 填充 listview；
        sgxm.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getListViewData(sgxm.getItemAtPosition(position).toString());
                setListViewAdapter();
                UpListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    //根据施工项目选择内容，从数据库读取数据（数据要填充到listview）
    private void getListViewData(String s) {
        int aqfxid = mMap.get(s);
        if (DBflag == 0) {
            mSecurityRiskDao = MyApplication.getDaoSession().getSecurityRiskDao();
            SecurityRiskList = mSecurityRiskDao.queryBuilder()
                    .where(SecurityRiskDao.Properties.SgxmId.eq(aqfxid))
                    .list();
            mListViewData.clear();
            for (SecurityRisk m : SecurityRiskList) {
                mListViewData.add(m.getAqfxNr());
            }

        }
        if (DBflag == 1) {
            //安全风险措施
            mProtectMeasuresDao = MyApplication.getDaoSession().getProtectMeasuresDao();
            ProtectMeasuresList = mProtectMeasuresDao.queryBuilder()
                    .where(ProtectMeasuresDao.Properties.SgxmId.eq(aqfxid))
                    .list();
            mListViewData.clear();
            for (ProtectMeasures m : ProtectMeasuresList) {
                mListViewData.add(m.getAqfhcsNr());
            }
        }

    }

    public void setListViewAdapter() {
        mMyListAdapter = new MyListAdapter();
        mList.setAdapter(mMyListAdapter);
    }

    //更新listview数据
    private void UpListView() {
        mMyListAdapter.notifyDataSetChanged();
    }

    //获取spinner数据
    public void getSpinnerData() {
        SpinnerList = new ArrayList<>();
        for (Map.Entry entry : mMap.entrySet()) {
            SpinnerList.add(entry.getKey().toString());
        }

    }

    //spinner设置数据源
    private void setSpinnerData() {
        sgxm.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_dropdown_item_1line, SpinnerList));
    }

    //根据选中checkbox改变textview内容
    public void UpSelectTextView() {
        select_text.setText("");
        String s = "";
        for (String mString : selectList) {
            s += mString + ",";
        }
        if (s.length() > 1) {
            s = s.substring(0, s.length() - 1);
        }
        select_text.setText(s);
    }

    //判断seleceList中是否存在该字段，若存在，则返回false 若不存在 则返回true
    public boolean IsAddselectList(String s) {
        boolean flag = true;
        for (String mString : selectList) {
            if (s.equals(mString))
                flag = false;
        }
        return flag;
    }

    @Override
    public void show() {
        super.show();
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        this.getWindow().setAttributes(lp);
    }

    public void setOnOkClickListener(OnOkClickListener mOnOkClickListener) {
        this.mOnOkClickListener = mOnOkClickListener;

    }

    public interface OnOkClickListener {
        void OkClickListener(String s, int viewId);
    }

    class MyListAdapter extends BaseAdapter {


        @Override
        public int getCount() {
            return mListViewData.size();
        }

        @Override
        public Object getItem(int position) {
            return mListViewData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View view, ViewGroup parent) {
            final ViewHolder mViewHolder;
            if (view == null) {
                view = View.inflate(getContext(), R.layout.bcfxd_listview, null);
                mViewHolder = new ViewHolder();

                mViewHolder.mCheckBox = (CheckBox) view.findViewById(R.id.checkbox);
                view.setTag(mViewHolder);
                mViewHolder.mCheckBox.setText(mListViewData.get(position));

            } else {
                mViewHolder = (ViewHolder) view.getTag();
                mViewHolder.mCheckBox.setText(mListViewData.get(position));
            }

            mViewHolder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        if (IsAddselectList(mViewHolder.mCheckBox.getText().toString())) {
                            selectList.add(mViewHolder.mCheckBox.getText().toString());
                            UpSelectTextView();
                        }
                    }
                    if (!isChecked) {
                        if (!IsAddselectList(mViewHolder.mCheckBox.getText().toString())) {
                            selectList.remove(mViewHolder.mCheckBox.getText().toString());
                            UpSelectTextView();
                        }
                    }
                }
            });
            return view;
        }

        class ViewHolder {
            CheckBox mCheckBox;
        }
    }
}
